const router = require('koa-router')()
const db = require('../utils/database')
const koaMulter = require('@koa/multer')
// 文件系统   node 内置
const fs = require('fs')
const path = require('path')
const md5 = require('md5-node')

// 前缀
router.prefix('/users')

// 查看当前文件所在文件夹
// console.log(path.join(__dirname))

// 文件上传相关配置
const storage = koaMulter.diskStorage({
    // 分发到某个文件夹
    destination: function (req, file, cb) {
        // 创建文件存放的目录
        try {
            const stat = fs.statSync(path.join(__dirname, '../upload-files'))
        } catch (e) {
            fs.mkdirSync('./upload-files')
        }
        cb(null, './upload-files')
    },
    // 图片名
    filename: function (req, file, cb) {
        const ext = file.originalname.split('.').pop()
        cb(null, file.fieldname + '-' + Date.now() + '.' + ext)
    }
})

const upload = koaMulter({
    storage
})

router.get('/', async ctx => {
    const r = await db.doSQL('select * from classify')
    ctx.body = 'users' + JSON.stringify(r)
})

// 根据令牌  获取用户信息
router.get('/user-info', async ctx => {
    const { token } = ctx.query
    const sql = 'select u.id,name,roles,avatar from users as u, tokens as t where t.token=? and t.uid=uid'
    const r = await db.doSQL(sql, [token])
    console.log(r)
    ctx.body = db.doResponse({ success: true, message: '用户信息', data: r[0] })
})

// 生成令牌
async function getTokenByUserId(id) {
    const sql_check = 'select * from tokens where uid=?'
    const r_check = await db.doSQL(sql_check, [id])
    if (r_check.length > 0) {
        return r_check[0].token
    } else {
        // md5加密   //TODO
        const token = md5('bkpx' + Date.now() + id + '01201202')
        const sql = 'insert into tokens (token,uid) values (?,?)'
        const r = await db.doSQL(sql, [token, id])
        return token
    }


}

// 用户登录
router.post('/user-login', async ctx => {
    const { username, password } = ctx.request.body
    const sql = 'select * from users where loginName=? and loginKey=?'
    const res = await db.doSQL(sql, [username, password])
    if (res.length > 0) {
        const token = await getTokenByUserId(res[0].id)
        ctx.body = db.doResponse({ success: true, message: '用户登录成功', data: { token } })

    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5002, message: '用户登录失败，用户名或密码错误', data: res })
    }
})




// fd.append('abc')  文件上传 form-data
// 用户头像上传   (修改方式)
router.post('/user-avatar', upload.single('avatar'), async ctx => {
    const { id } = ctx.request.body
    const sql = 'update users set avatar=? where id=?'
    const params = [ctx.file.filename, id]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ success: true, message: '用户头像上传成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5006, message: '用户头像上传失败', data: r })
    }
})

// 用户列表、分页、排序、查询
router.get('/user-list', async ctx => {
    const { page = 0, pageSize = 20, sortBy/* 根据谁排 */, order = 'asc' /* 排列顺序 */, query } = ctx.query
    // select * from limit 0, 3  (从第几行开始查  查几个)
    let sql = `select * from users`
    // 查询  select * from users where name like '张%'   张%  张开头 %张% 包含张  张_ 一个字张开头的
    if (query) {
        sql += ` where name like '%${query}%'`
    }
    // 排序
    if (sortBy) {
        sql += ` order by ${sortBy} ${order}`
    }
    sql += ` limit ${page * pageSize},${pageSize}`
    const r = await db.doSQL(sql)
    // select count(*) as total from users    total  总条数
    const sqlTotal = 'select count(*) as total from users'
    const rTotal = await db.doSQL(sqlTotal)
    const total = rTotal[0].total
    // select * from users order by id(age) asc(asc小到大/desc大到小)
    ctx.body = db.doResponse({ message: '用户列表', data: r, total: total })
})

// 删除用户
router.get('/delete-user', async ctx => {
    const { id } = ctx.query
    const sql = 'delete from users where id=?'
    const params = [id]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ success: true, message: '删除用户成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5001, message: '删除用户失败', data: r })
    }
})

// 修改用户
router.post('/update-user', async ctx => {
    const { name, age, gender, loginName, loginKey, id } = ctx.request.body
    const sql = 'update users set name=?,age=?,gender=?,loginName=?,loginKey=? where id=?'
    const params = [name, age, gender, loginName, loginKey, id]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ success: true, message: '修改用户成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5003, message: '修改用户失败', data: r })
    }
})

// 新增用户   什么时候用get什么时候用post   简单的解释： 拿数据get  往服务器发送数据post
router.post('/save-user', async ctx => {
    const { name, age, gender, loginName, loginKey } = ctx.request.body
    const sql = 'insert into users(name, age , gender,loginName,loginKey) values (?,?,?,?,?)'
    const params = [name, age, gender, loginName, loginKey]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: '新增用户成功', data: r })
    } else {
        ctx.body = db.doResponse({ success: false, errorCode: 5004, message: '新增用户失败', data: r })
    }
    // ctx.body = db.doResponse({ success: true, errorCode: 0, message: 'OK', date: r })

})

module.exports = router